﻿using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace PageOffice6_Net_Core.Controllers.ExtractImage
{
    public class ExtractImageController : Controller
    {
        private readonly IWebHostEnvironment _webHostEnvironment;

        public ExtractImageController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Word()
        {
            PageOfficeNetCore.PageOfficeCtrl poCtrl = new PageOfficeNetCore.PageOfficeCtrl(Request);

            PageOfficeNetCore.Word.WordDocumentWriter wordDoc = new PageOfficeNetCore.Word.WordDocumentWriter();
            PageOfficeNetCore.Word.DataRegionWriter dataRegion1 = wordDoc.OpenDataRegion("PO_image");
            dataRegion1.Editing = true;//放图片的数据区域是可以编辑的，其它部分不可编辑
            poCtrl.SetWriter(wordDoc);
            //打开Word文档
            poCtrl.WebOpen("doc/test.doc", PageOfficeNetCore.OpenModeType.docSubmitForm, "tom");
            ViewBag.poCtrl = poCtrl.GetHtml();
            return View();
        }


        public async Task<ActionResult> SaveData()
        {
            PageOfficeNetCore.Word.WordDocumentReader doc = new PageOfficeNetCore.Word.WordDocumentReader(Request, Response);
            await doc.LoadAsync();
            PageOfficeNetCore.Word.DataRegionReader dataRegion1 = doc.OpenDataRegion("PO_image");
            //将提取的图片保存到服务器上，图片的名称为:a.jpg

            string webRootPath = _webHostEnvironment.WebRootPath;
            dataRegion1.OpenShape(1).SaveAsJPG(webRootPath + "/ExtractImage/doc/a.jpg");
            //注册编码提供程序
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);


            //UrlEncoder
            doc.CustomSaveResult = HttpUtility.UrlEncode("保存成功,文件保存到：" + "wwwroot/ExtractImage/doc/a.jpg");
            return doc.Close();
            
        }
    }
}